
import socket
import subprocess
import struct
import json
phone = socket.socket()

phone.bind(('127.0.0.1', 8888))

phone.listen(5)

# 4. 接收连接
print('start')
conn, addr = phone.accept()
while 1:
    try:
        cmd = conn.recv(1024)
        obj = subprocess.Popen(cmd.decode('utf-8'),
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               )

        result = obj.stdout.read() + obj.stderr.read()
        result = result.decode('gbk').encode('utf-8')
        # print(f'服务端发送的总字节数{len(result)}')

        # 1. 制作报头

        head_dict = {
            'MD5': 'fdsaf2345544324dfs',
            'file_name': '婚前视频',
            'file_size': len(result),
        }

        # 2. 将报头字典转化成json字符串
        head_dict_json = json.dumps(head_dict)

        # 3. 将json字符串 转化成bytes
        head_dict_json_bytes = head_dict_json.encode('utf-8')

        # 4. 获取报头的长度
        head_len = len(head_dict_json_bytes)

        # 5.将长度转化成固定的4个字节
        head_len_bytes = struct.pack('i',head_len)

        # 6. 发送固定的4个字节
        conn.send(head_len_bytes)

        # 7. 发送报头
        conn.send(head_dict_json_bytes)

        # 8. 发送原数据
        conn.send(result)

    except ConnectionResetError:
        break
conn.close()
phone.close()

















